/*
 * @Descripttion: 
 * @version: 
 * @Author: wangzhilei
 * @Date: 2021-09-21 10:41:12
 * @LastEditors: wangzhilei
 * @LastEditTime: 2021-09-21 11:05:41
 */
#include "../config.h"
#define BUFLEN 255

int main(int argc, char **argv)
{
    struct sockaddr_in peeraddr,myaddr;
    int sockfd;
    char recmsg[BUFLEN + 1];
    unsigned int socklen;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        printf("socket creating err in udptalk\n");
        exit(EXIT_FAILURE);
    }
    //组播
    socklen=sizeof(struct sockaddr_in);
    bzero(&peeraddr,socklen);
    peeraddr.sin_family=AF_INET;
    peeraddr.sin_port=htons(PORT);//组播客户端绑定的端口
    //命令行参数1为组播地址
    if (argv[1])
    {
        if (inet_pton(AF_INET, argv[1], &peeraddr.sin_addr) <= 0)
        {
            printf("Wrong dest IP address!\n");
            exit(EXIT_FAILURE);
        }
    }
    else
    {
        printf("you should give me a group address,224.0.0.0-239.255.255.255\n");
        exit(EXIT_FAILURE);
    }
    //绑定本机IP和端口
    bzero(&myaddr,socklen);
    myaddr.sin_family=AF_INET;
    myaddr.sin_port=htons(23456);
    //命令行参数2为本机IP
    if (argv[2])
    {
        if (inet_pton(AF_INET,argv[2],&myaddr.sin_addr)<=0)
        {
            printf("self ip address error\n");
            exit(EXIT_FAILURE);
        }
    }else
        myaddr.sin_addr.s_addr=INADDR_ANY;
    
    if (bind(sockfd,(struct sockaddr *)&myaddr,sizeof(struct sockaddr_in))==-1)
    {
        printf("Bind error\n");
        exit(EXIT_FAILURE);
    }
    for(;;)
    {
        bzero(recmsg,BUFLEN+1);
        printf("input message to send:");
        if (fgets(recmsg,BUFLEN,stdin)==(char *)EOF)
        {
            exit(EXIT_FAILURE);
        }
        //发送组播消息
        if (sendto(sockfd,recmsg,strlen(recmsg),0,(struct sockaddr *)&peeraddr,sizeof(struct sockaddr_in))<0)
        {
            printf("sendto error\n");
            exit(EXIT_FAILURE);
        }
        printf("send message:%s",recmsg);
    }
}